
package com.rollway.restful.processor;


import com.rollway.restful.MethodMetadata;
import org.springframework.web.bind.annotation.RequestParam;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Map;

import static com.rollway.restful.utils.Util.checkState;
import static com.rollway.restful.utils.Util.emptyToNull;


public class RequestParamParameterProcessor implements AnnotatedParameterProcessor {

	private static final Class<RequestParam> ANNOTATION = RequestParam.class;

	@Override
	public Class<? extends Annotation> getAnnotationType() {
		return ANNOTATION;
	}

	@Override
	public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
		int parameterIndex = context.getParameterIndex();
		Class<?> parameterType = method.getParameterTypes()[parameterIndex];
		MethodMetadata data = context.getMethodMetadata();
		if (Map.class.isAssignableFrom(parameterType)) {
			checkState(data.getQueryMapIndex() == null, "Query map can only be present once.");
			data.setQueryMapIndex(parameterIndex);
			return true;
		}
		RequestParam requestParam = ANNOTATION.cast(annotation);
		String name = requestParam.value();
		checkState(emptyToNull(name) != null, "RequestParam.value() was empty on parameter %s", parameterIndex);
		context.getMethodMetadata().getQueryIndexAndName().put(parameterIndex,name);
		return true;
	}

}
